<?php
namespace app\ux;

use think\Db;

class UtilDb
{

    /**
     * 创建数据库
     *
     * @param string $tblname
     * @return int
     */
    public static function createDb($dbname)
    {
        try {
            $sql = "CREATE DATABASE " . $dbname;
            Db::execute($sql);
        } catch (\Exception $e) {
            throw new \think\Exception($e->getMessage());
        }
    }
    /**
     * 查数据库表
     *
     * @param string $dbname
     * @return array table array
     */
    public static function showTables($dbname = null)
    {
        try {

            $sql = !empty($dbname) ? "SHOW TABLE STATUS FROM " . $dbname : "SHOW TABLES";
            $res = Db::query($sql);
            if ($res) {
                $temp   = array_keys($res[0]);
                $column = $temp[0];
                return array_column($res, $column);
            } else {
                return array();
            }
        } catch (\Exception $e) {
            throw new \think\Exception($e->getMessage());
        }
    }

    /**
     * 清空数据库表
     *
     * @param string $tblname 表名
     * @return void
     */
    public static function truncateTable($tblname)
    {
        try {
            $sql = "TRUNCATE TABLE " . $tblname;
            Db::execute($sql);
        } catch (\Exception $e) {
            throw new \think\Exception($e->getMessage());
        }
    }

    /**
     * 删除数据库表列
     *
     * @param string $tblname 表名
     * @param string $field 自增字段
     * @return void
     */
    public static function dropTableColumn($tblname, $field)
    {
        try {
            $sql = "ALTER TABLE " . $tblname . " DROP COLUMN " . $field;
            Db::execute($sql);
        } catch (\Exception $e) {
            throw new \think\Exception($e->getMessage());
        }
    }

    /**
     * 为数据库表增加自增列
     *
     * @param string $tblname 表名
     * @param string $field 自增字段
     * @return void
     */
    public static function addPK($tblname, $field)
    {
        try {
            $sql = "ALTER TABLE " . $tblname . " ADD " . $field . " INT auto_increment NOT NULL, ADD PRIMARY KEY(" . $field . ")";
            Db::execute($sql);
        } catch (\Exception $e) {
            throw new \think\Exception($e->getMessage());
        }
    }

    /**
     * 清空数据库表删除自增主键列之后,重新为表增加自增主键列
     *
     * @param string $tblname 表名
     * @param string $field 自增字段
     * @return void
     */
    public static function clearTable($tblname, $field)
    {

        self::truncateTable($tblname);
        self::dropTableColumn($tblname, $field);
        self::addPK($tblname, $field);
    }

}
